package com.itboye.mengwu.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.cache.ACache;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.logincontroller.LoginController;
import com.itboye.mengwu.app.logincontroller.LoginedState;
import com.itboye.mengwu.app.logincontroller.UnLoginState;
import com.itboye.mengwu.app.ui.aiwujia.ActivityAiwujiaMomPublish;
import com.itboye.mengwu.app.ui.main.MainPresenter;
import com.itboye.mengwu.data.presenter.LogGinPresenter;
import com.itboye.mengwu.widget.NetState;
import com.umeng.message.PushAgent;

import java.util.Observable;
import java.util.Observer;

@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements Observer,
        OnClickListener, android.widget.CompoundButton.OnCheckedChangeListener {

    private Button btnTest;
    int temp;
    public static int WIDTH;
    private MainPresenter presenter;
    ACache aCache;// 缓存类
    RadioGroup group;
    public Fragment[] fr;
    // private RadioGroup tab_radiogroup;
    private RadioButton[] mTabs;
    private int index;
    private int mCurrIndex;
    int count;
    ImageView zengwuxian_img;
    String uid;
    RelativeLayout fragment_container;
    static LogGinPresenter presenterto;

    String uidto, locode;
    private ProgressDialog mProgressDialog;
    private final static String TAGS[] = new String[]{"near", "conv",
            "paotui", "gouwuhce", "wo"}; // fragments的tag
    private final static int Tab_Cnt = 5; // 5个tab页
    MainApplication mainApplication;

    public void generate() {
        int baseW = 640;
        int baseH = 960;
        String addition = "";

    }

    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("执行了2");
            int selectIndex = intent.getIntExtra("index", 0);
            System.out.println("selectIndex" + selectIndex);
            index = selectIndex;
            temp = index;
            setCurrentTab();
        }
    };

    @Override
    public void onMyCreate() {
        mainApplication = (MainApplication) getApplication();
        mainApplication.mainUI = this;
        presenterto = new LogGinPresenter(this);
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width2 = outMetrics.widthPixels;
        WIDTH = (int) (outMetrics.widthPixels);
        IntentFilter filter = new IntentFilter("set");
        registerReceiver(receiver, filter);
        aCache = ACache.get(this);// 得到缓存对象
        if (isNetworkAvailable(MainActivity.this)) {
            // true
        } else {
            ByAlert.alert("暂时无网络，请查看网络设置");
            return;
        }
        try {
            PushAgent.getInstance(getApplicationContext()).enable();
        } catch (Exception e) {

        }
        if (!((Boolean) SPUtils.get(MainApplication.context, null,
                SpPublicParams.IS_LOGINED, false)) || (SPUtils.get(MainApplication.context, null,
                SpPublicParams.UID, "")).equals("")) {
            LoginController.setLoginState(new UnLoginState());
        } else {
            LoginController.setLoginState(new LoginedState());
        }
        IntentFilter AutoLoginfilter = new IntentFilter("onLogin");
        registerReceiver(broadcastReceiverTopS, AutoLoginfilter);
        generate();
        initUI();
        initFragments();
    }

    BroadcastReceiver broadcastReceiverTopS = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            onLogin();
        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState,
                                    PersistableBundle outPersistentState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public int initView() {
        // 注册广播接收器Start
        NetState receiver = new NetState();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver, filter);
        receiver.onReceive(this, null);
        // 注册广播接收器End

        // TODO Auto-generated method stub
        return R.layout.activity_main;
    }

    @Override
    protected void onSaveInstanceState(Bundle arg0) {
        // TODO Auto-generated method stub
        // super.onSaveInstanceState(arg0);不注释掉，一旦程序出现bug,界面将出现重叠
    }

    public void onLogin() {
        uidto = SPUtils.get(MainActivity.this, null, SpPublicParams.UID, "") + "";
        locode = SPUtils.get(MainActivity.this, null, SpPublicParams.SESSION_CODE, "") + "";
        if (uidto.equals("") || uidto == null) {

        } else {
            presenterto.OnLogin(uidto, locode);
        }
    }


    @Override
    public void update(Observable observable, Object data) {
        if (count == 0) {
            zengwuxian_img.setBackgroundResource(R.drawable.mamzengsong);
        } else if (count >= 1) {
            zengwuxian_img.setBackgroundResource(R.drawable.fabu);
        }
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == presenterto.AddGoods_success) {
                System.out.println(entity.getData() + ">>>>自动登录");
                if (entity.getData().equals("false")) {
                    exit();
                    setCurrentUI(false);
                    closeAllUI();
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
//                    Intent intenttop = new Intent("changeavartTop");
//                    sendBroadcast(intenttop);
//                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                    startActivity(intent);
//                    exit();
                }

            }
        }
    }

    private void closeAllUI() {
        mainApplication.getGetInstance().exit();
    }

    public void setCurrentUI(boolean isActivated) {
        if (isActivated) {
            mainApplication.mainUI = this;
        } else {
            mainApplication.mainUI = null;
        }
    }

    private void exit() {
        // TODO Auto-generated method stub
        try {
            PushAgent.getInstance(MainApplication.context).deleteAlias(
                    (String) SPUtils.get(MainApplication.context, null,
                            SpPublicParams.UID, ""), "mengwu");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        SPUtils.put(MainApplication.context, null, SpPublicParams.USER_NAME, "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.USERHEAD, "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.NICK_NAME, "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.UID, "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.SEX, "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.SIGNATURE, "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.PHONE_MODEL,
                "");
        SPUtils.put(MainApplication.context, null, SpPublicParams.IS_LOGINED,
                false);

        SPUtils.put(MainApplication.context, null, SpPublicParams.VIP, "");
        LoginController.setLoginState(new UnLoginState());
        Intent intent = new Intent(WoMengFragment.AVARTACTION);
        sendBroadcast(intent);
        Intent intent2 = new Intent("changeshopcart");
        sendBroadcast(intent2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String keyStr = data.getStringExtra("key");

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.zengwuxian_img:
                zengwuxian_img.setBackgroundResource(R.drawable.fabu);
                count++;
                index = 2;
                setCurrentTab();
                Log.e("hu...img", count + "");
                if (count >= 1) {

                    uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
                    if ("".equals(uid) | uid == null) {
                        Intent intent = new Intent(this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(this,
                                ActivityAiwujiaMomPublish.class);
                        startActivity(intent);
                    }
                }
                break;
            default:
                break;
        }

    }


    private void initUI() {


        // tab_radiogroup = (RadioGroup) findViewById(R.id.tab_radiogroup);
        mTabs = new RadioButton[Tab_Cnt];
        mTabs[0] = (RadioButton) findViewById(R.id.radio_button0);
        mTabs[1] = (RadioButton) findViewById(R.id.radio_button1);
        mTabs[2] = (RadioButton) findViewById(R.id.radio_button2);
        mTabs[3] = (RadioButton) findViewById(R.id.radio_button3);
        mTabs[4] = (RadioButton) findViewById(R.id.radio_button4);
        for (RadioButton bt : mTabs) {
            bt.setOnCheckedChangeListener(this);
        }

    }

    private void setCurrentTab() {
        if (mCurrIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager()
                    .beginTransaction();
            trx.hide(fr[mCurrIndex]);
            if (!fr[index].isAdded()) {
                trx.replace(R.id.fragment_container, fr[index]);
            }
            trx.show(fr[index]).commitAllowingStateLoss();
            mTabs[mCurrIndex].setChecked(false);
            mCurrIndex = index;
            if (!mTabs[mCurrIndex].isChecked()) {
                mTabs[mCurrIndex].setChecked(true);// 不会重复触发setCurrentTab
            }

        }
        if (count == 0 && index != 2) {
            zengwuxian_img.setBackgroundResource(R.drawable.mamzengsong);
        } else {

            zengwuxian_img.setBackgroundResource(R.drawable.fabu);
        }
    }

    void initFragments() {
        // TodaySpecialOfferFragmentActivity f1 = null;
        // AiWuJia f2 = null;MengMengCheFragmentActivity f3 =
        // null;ShopCarActivity f4 = null;MengFragment f5 = null;
        fr = new Fragment[]{new HomeFragment(), new AizhiwuFragment(),
                new MomZengFragement(), new FragmentShopcart(),
                new WoMengFragment()};

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, fr[0], TAGS[0])
                .add(R.id.fragment_container, fr[1], TAGS[1])
                .add(R.id.fragment_container, fr[2], TAGS[2])
                .add(R.id.fragment_container, fr[3], TAGS[3])
                .add(R.id.fragment_container, fr[4], TAGS[4]).hide(fr[1])
                .hide(fr[2]).hide(fr[3]).hide(fr[4]).show(fr[mCurrIndex])
                .commit();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.radio_button0:
                    index = 0;
                    count = 0;
                    break;
                case R.id.radio_button1:
                    count = 0;
                    index = 1;
                    break;
                case R.id.radio_button2:
                    count = 0;
                    index = 2;
                    break;
                case R.id.radio_button3:
                    count = 1;
                    index = 3;
                    zengwuxian_img.setBackgroundResource(R.drawable.fabu);
                    break;
                case R.id.radio_button4:
                    count = 0;
                    index = 4;
                    try {
                        WoMengFragment.setPosition();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    break;
                default:
                    break;
            }
            temp = index;
            setCurrentTab();
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    System.out.println(i + "===状态==="
                            + networkInfo[i].getState());
                    System.out.println(i + "===类型==="
                            + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
